package com.kgc.storeconsumer.controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.store.pojo.CostAdjustment;
import com.kgc.store.remote.CostAdjustmentRemote;
import com.kgc.storeconsumer.feign.CostAdjustmentFeign;
import com.kgc.storeconsumer.feign.CostAdjustmentWorkFlowFeign;
import com.kgc.storeconsumer.feign.ImportExportFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Controller
@CrossOrigin("*")
@RequestMapping("/proChange")
public class CostAdjustmentController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CostAdjustmentFeign costAdjustmentFeign;
    @Autowired
    private CostAdjustmentWorkFlowFeign costAdjustmentWorkFlowFeign;
    @Autowired
    private ImportExportFeign importExportFeign;

    @RequestMapping("getOne")
    @ResponseBody
    public ResponseMsg getOne(String code){
        logger.info("CostAdjustmentController getOne code:"+code);
        ResponseMsg responseMsg =costAdjustmentFeign.getOne(code);
        logger.debug("CostAdjustmentController getOne responseMsg:"+responseMsg+",id:"+code);
        return responseMsg;
    }
    @RequestMapping("getPage")
    @ResponseBody
    public ResponseMsg getPage(String pageNow, String pageSize, String code, String status, String startDate,String endDate){
    logger.info("CostAdjustmentController getPage pageNow:"+pageNow+" pageSize:"+pageSize+" code:"+code+" status:"+status+" startDate:"+startDate+" endDate:"+endDate);
    Map<String,Object> map = new HashMap<>();
    map.put("code",code);
    map.put("status",status);
    map.put("startDate",startDate);
    map.put("endDate",endDate);
    map.put("pageNow",pageNow);
    map.put("pageSize",pageSize);
    ResponseMsg responseMsg = costAdjustmentFeign.getPage(map);
    logger.debug("costAdjustmentFeign getPage responseMsg:"+responseMsg+",map:"+map);
    return responseMsg;
    }
    @RequestMapping("add")
    @ResponseBody
    public ResponseMsg add(@RequestBody CostAdjustment costAdjustment){
    logger.info("CostAdjustmentController add costAdjustment:"+costAdjustment);
    Map<String,Object> variables = new HashMap<>();
    variables.put("code",costAdjustment.getCode());//单据编号
    variables.put("type",costAdjustment.getTypeId());//流程类型
    costAdjustmentWorkFlowFeign.startProcess(variables);
    ResponseMsg responseMsg = costAdjustmentFeign.add(costAdjustment);
    logger.debug("costAdjustmentFeign add responseMsg:"+responseMsg+",costAdjustment:"+costAdjustment);
    return responseMsg;
    }
    @RequestMapping("update")
    @ResponseBody
    public ResponseMsg update(@RequestBody CostAdjustment costAdjustment){
    logger.info("CostAdjustmentController update costAdjustment:"+costAdjustment);
    ResponseMsg responseMsg = costAdjustmentFeign.update(costAdjustment);
    logger.debug("costAdjustmentFeign update responseMsg:"+responseMsg+",costAdjustment:"+costAdjustment);
    return responseMsg;
    }
    @RequestMapping("del")
    @ResponseBody
    public ResponseMsg del(String code){
    logger.info("CostAdjustmentController del code:"+code);
    ResponseMsg responseMsg = costAdjustmentFeign.del(code);
    logger.debug("costAdjustmentFeign del responseMsg:"+responseMsg+",code:"+code);
    return responseMsg;
    }
    @RequestMapping("/check")
    @ResponseBody
    public  ResponseMsg check(@RequestBody Map<String,Object> map){
        ResponseMsg responseMsg = new ResponseMsg();
        logger.info("SalesOrdersController check params,{}",map.toString());
        Map<String,Object> variables = new HashMap<>();
        variables.put("code",(String) map.get("code"));//单据编号
        variables.put("checkManId",(Integer) map.get("checkManId"));//审批人
        variables.put("checkManName",(String) map.get("checkManName"));//审批人
        variables.put("checkComment",(String) map.get("checkComment"));//审批意见
        variables.put("checkDate",new Date());//审批时间
        variables.put("checkRes",(boolean)map.get("checkRes"));//审批结果
        com.kgc.activiti.util.ResponseMsg msg=  costAdjustmentWorkFlowFeign.competeTask(variables);
        responseMsg.setCode(msg.getCode());
        responseMsg.setMsg(msg.getMsg());
        return responseMsg;
    }
    @RequestMapping(value = "/export")
    public void exportSalesInvoices(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesInvoiceController exportSalesInvoices params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.store.pojo.CostAdjustment", "create_date desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("成本调整信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesInvoiceController exportSalesInvoices is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    //下载模板
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) {
        logger.info("consumer CustomerController downTemplate is start...");
        try {
            ResponseMsg responseMsg = importExportFeign.downLoadTemplate("com.kgc.store.pojo.CostAdjustment");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] templateData = Base64.getDecoder().decode(base64Data);   //解码

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("成本调整表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(templateData);
            } else {
                logger.error("下载模板失败, status: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer CustomerController downTemplate is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    //导入
    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer CustomerController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.store.pojo.CostAdjustment", "code", "");
    }
    @RequestMapping("/changePrice")
    @ResponseBody
    public ResponseMsg changePrice(@RequestBody CostAdjustment costAdjustment){
        logger.info("consumer CustomerController changePrice costAdjustment:{}", costAdjustment);
        ResponseMsg responseMsg = costAdjustmentFeign.changePrice(costAdjustment);
        logger.debug("costAdjustmentFeign changePrice responseMsg:"+responseMsg);
        return responseMsg;
    }
}
